/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useEffect, useRef, useState } from 'react';
import { Divider, List, Button, Spin, message } from 'antd';
import { ModalForm, ProFormTextArea } from '@ant-design/pro-form';
import type { ProFormInstance } from '@ant-design/pro-form';
import request from '@/utils/request';
import styles from './index.less';
import { isArray } from 'lodash';

interface remarkList {
  remark: string;
  label: string;
  time: string;
  user: string;
}
interface KbCollectionModal {
  api: string;
  formData: any;
  listApi: string;
  listFormData: any;
  visible: boolean;
  setVisible: (visible: boolean) => void;
  modalTitle?: string;
  headerTitle?: string;
  required?: boolean;
  formatDataMap: remarkList;
}

const Index = ({
  api,
  formData,
  listApi,
  listFormData,
  visible,
  setVisible,
  modalTitle = '历史记录',
  headerTitle,
  required,
  formatDataMap,
}: KbCollectionModal) => {
  const formRef = useRef<ProFormInstance>();
  const [remarkList, setRemarkList] = useState<remarkList[]>([]);
  const [loading, setLoading] = useState<boolean>(false);

  const getList = () => {
    request(listApi, {
      method: 'POST',
      data: listFormData,
    }).then((res) => {
      const { code, data } = res;
      setLoading(false);
      if (code == 0 && isArray(data)) {
        console.log(formRef, '----');
        const list: any = data.map((item: remarkList) => {
          const remarkItem = {};
          Object.keys(formatDataMap).forEach((item1) => {
            remarkItem[item1] = item[formatDataMap[item1]] || '';
          });
          return remarkItem;
        });
        setRemarkList(list);
      } else {
        setRemarkList([]);
      }
    });
  };
  const onSubmit = async (data: { remark: string }) => {
    if (loading) return;
    setLoading(true);
    request(api, {
      method: 'POST',
      data: { ...data, ...formData },
    }).then((res) => {
      const { code, msg } = res;
      if (code === 0) {
        getList();
        formRef.current?.resetFields();
        message.success(msg);
      } else {
        message.error(msg);
      }
    });
  };

  useEffect(() => {
    if (visible) getList();
  }, [visible]);
  return (
    <ModalForm
      className={styles.collectionModal}
      formRef={formRef}
      title={modalTitle}
      visible={visible}
      onFinish={onSubmit}
      onVisibleChange={setVisible}
      submitter={{
        render: ({ form }) => (
          <Button type='primary' onClick={() => form?.submit()}>
            保存
          </Button>
        ),
      }}
      modalProps={{
        bodyStyle: { padding: 0, height: 500 },
      }}
    >
      <Spin spinning={loading}>
        <div
          id='scrollableDiv'
          style={{
            height: 400,
            overflow: 'auto',
            padding: '0 16px',
          }}
        >
          <List
            header={headerTitle ? <h3>{headerTitle}</h3> : ''}
            dataSource={remarkList}
            itemLayout='horizontal'
            renderItem={(item, index) => (
              <List.Item key={index}>
                <List.Item.Meta
                  title={item.remark}
                  description={
                    item.label +
                    (item.label && ' - ') +
                    item.user +
                    (item.user && ' - ') +
                    item.time
                  }
                />
              </List.Item>
            )}
          />
          <Divider plain>没有更多了 🤐</Divider>
        </div>
        <ProFormTextArea
          name='remark'
          placeholder='请输入备注内容'
          allowClear
          rules={required ? [{ required: true, message: '请输入备注内容' }] : []}
          fieldProps={{
            rows: 4,
            maxLength: 300,
          }}
        />
      </Spin>
    </ModalForm>
  );
};

export default Index;
